//
//  ViewController.swift
//  sweepMine
//
//  Created by 孙飞 on 15/12/17.
//  Copyright © 2015年 Sunfei. All rights reserved.
//

import UIKit
import SnapKit

var colNumb: Int = 8
var mineSetCount: Int = 12

let sumCount = colNumb * colNumb

let mineBtnW = (SCREENW - CGFloat(colNumb+1)) / CGFloat(colNumb)
let mineMargin = 1

var safeCellCount = 0   //记录已经确认安全的cell的个数

class ViewController: UIViewController {

    ///雷数组
    var mineCells: [mineModel]?
    var numbOfMine: [Int]?
    var mineBtn: MXSButton?
    
    ///随机 编号
    static var mmmm: Int = 0
    func mineNumbSetting(){
        
        numbOfMine = [Int]()
        for _ in 0..<mineSetCount{
            // 随机出一个 0-64 数字
            var Numb = Int(arc4random()) % sumCount
            while numbOfMine!.contains(Numb){
                Numb = Int(arc4random()) % sumCount
            }
            numbOfMine!.append(Numb)
        }
    }
    
    /// 布局
    func mineCellSetting(){
        
        mineCells = [mineModel]()
        for i in 0..<sumCount{
            let mineCell = mineModel()
            mineCell.numb = i
            //取出雷区分布图，遍历雷区，判断cell是否要埋雷
            mineCell.mineIcon = "safe"
            mineCell.isHiddenMine = true
            mineCell.isHiddenCount = true
            mineCell.isMine = false
            for j in 0..<mineSetCount{
                if i == numbOfMine![j] {
                    mineCell.mineIcon = "boom"
                    mineCell.isMine = true
                    break
                }
            }
            mineCells?.append(mineCell)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.grayColor()
        
        setupUI()
    }
    
    func setupUI(){
        
        view.addSubview(border_BG)
        view.addSubview(mineArea)
        view.addSubview(resetBtn)
        view.addSubview(rangSettingBtn)
        
        border_BG.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view.snp_top).offset(60)
            make.leading.equalTo(view.snp_leading)
            make.width.equalTo(SCREENW)
            make.height.equalTo(SCREENW+8)
        }
        
        mineArea.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view.snp_top).offset(64)
            make.leading.equalTo(view.snp_leading)
            make.width.equalTo(SCREENW)
            make.height.equalTo(SCREENW)
        }
        
        //重置按钮
        resetBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(border_BG.snp_bottom).offset(30)
            make.leading.equalTo(view.snp_leading).offset(30)
            make.width.equalTo(120)
            make.height.equalTo(30)
        }
        //设置等级按钮
        rangSettingBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(border_BG.snp_bottom).offset(30)
            make.right.equalTo(view.snp_right).offset(-30)
            make.width.equalTo(120)
            make.height.equalTo(30)
        }
        
        resetBtn.addTarget(self, action: "resetting", forControlEvents: UIControlEvents.TouchUpInside)
        rangSettingBtn.addTarget(self, action: "rangSetting", forControlEvents: UIControlEvents.TouchUpInside)
        
        //UILongPressGestureRecognizer(长按)
        // 创建手势对象
        let mylongPress = UILongPressGestureRecognizer(target: self, action: "mylongPress:")
        mylongPress.minimumPressDuration = 1  // 长按的事件
        mylongPress.allowableMovement = 50    // 误差范围
        
        // 添加到某个view上
        mineArea.addGestureRecognizer(mylongPress)
        
        mineNumbSetting()
        mineCellSetting()
        
        ///初始化雷数组
        updateMineData()
    }
    
    func mylongPress(sender : UILongPressGestureRecognizer)
    {
        // 判断如果是开始的状态那么执行某些代码
        if sender.state == UIGestureRecognizerState.Began {
            print("longpress");
        }
    }
    
    func updateMineData(){
        
        //移除所有子控件
        mineArea.subviews.map{ $0.removeFromSuperview() }
        
        for i in 0..<sumCount {
            
            let row = i / colNumb
            let col = i % colNumb
            
            let x = mineBtnW * CGFloat(col) + CGFloat(mineMargin * (1 + col))
            let y = mineBtnW * CGFloat(row) + CGFloat(mineMargin * (1 + row))
            
            mineBtn = MXSButton(frame: CGRect(x: x, y: y, width: mineBtnW, height: mineBtnW))
            
            mineBtn!.mine = mineCells![i]
            
            mineBtn!.addTarget(self, action: "didSweepMine:", forControlEvents: UIControlEvents.TouchUpInside)
            
            self.mineArea .addSubview(mineBtn!)
        }
    }
    
    func didSweepMine(mineBtn: MXSButton){
//        mineBtn.enabled = false
//        print("sweepping mine")
        
        //计算方法提取到了common中
        caculateAroundMinecount(mineBtn.mine!.numb, mineCells: mineCells!)
        
        //记录已经确认 不是雷的格
        
        
        if mineBtn.mine!.isMine == true {
            
            for i in 0..<sumCount{
                //
                mineCells![i].isHiddenMine = false
            }
            updateMineData()
            
//            //失败之后 是否要让用户自己去点击 重置按钮，还是弹框提示，弹框会遮住失败之后展示给用户的 雷区分布图
//            let alertView = UIAlertController(title: "提示", message: "游戏结束", preferredStyle: UIAlertControllerStyle.Alert)
//            
//            alertView.addAction(UIAlertAction(title: "确定", style:UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
//                
//                self.mineNumbSetting()
//                self.mineCellSetting()
//                self.updateMineData()
//            }))
//            
//            self.presentViewController(alertView, animated: true, completion: nil)
        }else {
            safeCellCount += 1
//            print(safeCellCount)
            if safeCellCount == sumCount - mineSetCount {
                let alertView = UIAlertController(title: "提示", message: "恭喜通关！", preferredStyle: UIAlertControllerStyle.Alert)
                
                alertView.addAction(UIAlertAction(title: "确定", style:UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
                    
                    self.mineNumbSetting()
                    self.mineCellSetting()
                    self.updateMineData()
                }))
                
                self.presentViewController(alertView, animated: true, completion: nil)
            }
        }
        mineBtn.mine?.isHiddenMine = false
        mineBtn.mine?.isHiddenCount = false
        
        updateMineData()
        
    }
    
    func resetting(){
        
        //重置： 重新设置哪些格有雷--添加雷区（九宫格）--更新数据
        self.mineNumbSetting()
        self.mineCellSetting()
        self.updateMineData()
    }
    
    func rangSetting(){
        let alertView = UIAlertController(title: "选择级别", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
        
        alertView.addAction(UIAlertAction(title: "菜鸟级", style:UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
            colNumb = 6
            mineSetCount = 12
            self.mineNumbSetting()
            self.mineCellSetting()
            self.updateMineData()
        }))
        alertView.addAction(UIAlertAction(title: "高手级", style:UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
            colNumb = 8
            mineSetCount = 21
            self.mineNumbSetting()
            self.mineCellSetting()
            self.updateMineData()
        }))
        alertView.addAction(UIAlertAction(title: "大师级", style:UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in
            colNumb = 10
            mineSetCount = 33
//            print("设置大师级")
            self.mineNumbSetting()
            self.mineCellSetting()
            self.updateMineData()
        }))
        alertView.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: nil))
        
        self.presentViewController(alertView, animated: true, completion: nil)
    }
    
    // MARK: - 懒加载控件
    private lazy var border_BG: UIView = {
        
        let border_BG = UIView()
        border_BG.backgroundColor = UIColor.blackColor()
        return border_BG
    }()
    
    private lazy var mineArea: UIView = {
        
        let mineArea = UIView()
        mineArea.backgroundColor = UIColor.blackColor()
        return mineArea
    }()
    private lazy var resetBtn: UIButton = {
        
        let resetBtn = UIButton()
        resetBtn.backgroundColor = UIColor.orangeColor()
        resetBtn.setTitle("重新开始", forState: UIControlState.Normal)
        return resetBtn
    }()
    private lazy var rangSettingBtn: UIButton = {
        
        let rangSettingBtn = UIButton()
        rangSettingBtn.backgroundColor = UIColor.orangeColor()
        rangSettingBtn.setTitle("等级设置", forState: UIControlState.Normal)
        return rangSettingBtn
    }()
    
    
    


}

